package com.casting;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXML {

	
	public static void main(String[] args) 
			throws ParserConfigurationException, SAXException, IOException {
		  //1.创建DOM解析器工厂
		  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		  //2.由DOM解析器工厂创建DOM解析器
		  DocumentBuilder db = dbf.newDocumentBuilder();
		  //3.由DOM解析器解析文档，生成DOM树
		  Document doc = db.parse("pom.xml");
		  //4.解析DOM树，获取文档内容（元素 属性 文本）
		  //4.1获取根元素scores
		  NodeList scoresList = doc.getChildNodes();
		  Node scoresNode = scoresList.item(1);
		  System.out.println(scoresList.getLength());
		  //4.2获取scores中所有的子元素student
		  NodeList studentList = scoresNode.getChildNodes();
		  System.out.println(studentList.getLength());
		  //4.3对每个student进行处理
		  for(int i=0;i<studentList.getLength();i++){
		   Node stuNode = studentList.item(i);
		   //System.out.println(stuNode.getNodeType());
		   //输出元素的属性 id
		   if(stuNode.getNodeType()==Node.ELEMENT_NODE){
		    Element elem =(Element)stuNode;
		    String id= elem.getAttribute("id");
		    System.out.println("id------>"+id);
		   }
		   //输出元素的子元素 name course score
		   NodeList ncsList = stuNode.getChildNodes();
		   //System.out.println(ncsList.getLength() );
		   for(int j=0;j<ncsList.getLength();j++){
		    Node ncs = ncsList.item(j);
		    if(ncs.getNodeType() == Node.ELEMENT_NODE){
		      String name = ncs.getNodeName();
		      //String value = ncs.getFirstChild().getNodeValue();//文本是元素的子节点，所以要getFirstChild
		      String value = ncs.getTextContent();
		      System.out.println(name+"----->"+value);
		    }
		   }
		   System.out.println();
		  }
		 }
	/*public static void main(String[] args) {
		ReadXML readXML = new ReadXML("pom.xml");
		System.out.println(readXML.getDrivername());
	}*/
}
